#ifndef MESSAGESDB_H
#define MESSAGESDB_H

#include "CoreFarmAPI.h"


/////////////////////////////////////////////////////
//////MESSAGE NODE AND METHODS///////////////////////
////////////////////////////////////////////////////

typedef struct MessagesNode{

	char messages[MESSAGE_LENGTH];
	int ID;
	struct MessagesNode* next;

}MessagesNode;


MessagesNode* MessagesNodeConstructor(){

	MessagesNode *thisNode;

	thisNode = (MessagesNode*)malloc(sizeof(MessagesNode));
	assertMem(thisNode);

	thisNode->ID = 0;
	thisNode->next = NULL;

	return thisNode;

}

void messagesNodeSetID( MessagesNode *thisNode, int _ID) { thisNode->ID =_ID ; }
void messagesNodeSetMSG( MessagesNode *thisNode, char *_MSG) { strcpy( thisNode->messages, _MSG ) ;}
void messagesNodeSetNext( MessagesNode *thisNode, MessagesNode *_next) { thisNode->next = _next ;}
char *messagesNodeGetMSG( MessagesNode *thisNode) {return thisNode->messages ;}
int messagesNodeGetID( MessagesNode *thisNode) {return thisNode->ID ;}
MessagesNode * messagesNodeGetNext( MessagesNode *thisNode) { return thisNode->next ;}

//////////////////////////////////////////////////////////////////////////////////
//////// Messages Database List structure and methods ////////////////////////////
//////////////////////////////////////////////////////////////////////////////////

typedef struct MessagesDB{

	int size;
	MessagesNode *head;

}MessagesDB;

MessagesDB *messages_DB = NULL;

void messagesDBConstructor(){
	messages_DB = (MessagesDB*)malloc(sizeof(MessagesDB));
	assertMem( messages_DB );
	
	messages_DB->size = 0;
	messages_DB->head = NULL;
}

void messagesDBSetHead(MessagesNode *_head){ messages_DB->head = _head ;}
MessagesNode* messagesDBGetHead(){ return messages_DB->head ;}
int messagesDBIsEmpty(){ return (messages_DB->size == 0) ;}

void messagesDBPush(char *MSG, int ID){

	MessagesNode *newMessages = MessagesNodeConstructor();

	messagesNodeSetMSG( newMessages, MSG);
	messagesNodeSetID( newMessages, ID);

	if ( !messages_DB )
		messagesDBConstructor();

	if( !messagesDBIsEmpty() )
		newMessages->next = messages_DB->head;

	messages_DB->head = newMessages;
	messages_DB->size++;
}

void messagesDBRemoveAllMessages(int serverID){
	MessagesNode *currNode = NULL, *prevNode = NULL;

	if( messages_DB )
		currNode = messages_DB->head;

	while( currNode )
	{
		if( serverID == currNode->ID )
		{
			if(prevNode)
				prevNode->next = currNode->next;
			else
				messages_DB->head = currNode->next;
		}
		prevNode = currNode;
		currNode = currNode->next;
	}
}

void messagesPrintAll(){
	MessagesNode *currNode = NULL;

	if ( messages_DB )
		currNode = messages_DB->head;
	while( currNode ){
		printf("ID: %d \n Messages:\n %s\n",currNode->ID, currNode->messages);
		currNode = currNode->next;
	}//while
}//meessagesPrintALL


#endif